package com.android.delivery.activity.wangdian

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.android.delivery.R
import com.android.delivery.adapter.wangdian.RiderManagementAdapter
import com.android.delivery.api.ApiService
import com.android.delivery.base.BaseListActivity
import com.android.delivery.callback.DialogCallback
import com.android.delivery.callback.LzyResponse
import com.android.delivery.constant.Constants
import com.android.delivery.entity.User
import com.android.delivery.util.ToastUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnConfirmListener
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.search_refresh_layout_list.*

/**
 * @author: mqwang
 * @create: 3/20/21 7:37 AM
 * @Description: 骑手管理
 */
class RiderManagementActivity : BaseListActivity<User>() {

    companion object {
        val TYPE_MANAGER: Int = 0
        val TYPE_TRANSFER: Int = 1
        val TYPE_DISPATH_TRANSFER: Int = 2
    }

    val EDIT_REQUESTCODE = 1;
    var mType: Int = 0
    var mLogisticNo: String? = ""
    private val riderManagementAdapter: RiderManagementAdapter by lazy {
        RiderManagementAdapter()
    }

    override fun init(savedInstanceState: Bundle?, container: View?) {
        mType = intent.getIntExtra(Constants.TYPE, 0)
        mLogisticNo = intent.getStringExtra(Constants.ORDER_ID)
        super.init(savedInstanceState, container)
    }

    override fun getLayoutId(): Int {
        return R.layout.search_refresh_layout_list
    }

    override fun bindRecyclerView(recLv: RecyclerView?) {
        setMainTitle("骑手管理")
        setSubTitle("添加骑手")
        if (mType == TYPE_TRANSFER || mType == TYPE_DISPATH_TRANSFER) {
            search_cly.visibility = View.VISIBLE
            bottom_view.visibility = View.VISIBLE
            et_search.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    onRefresh(refreshLayout)
                }

                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }

            })
            et_search.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onRefresh(refreshLayout)
                    return@OnEditorActionListener true
                }
                false
            })
            tv_send.setOnClickListener {
                val selectItem = riderManagementAdapter.getselectItem()
                if (selectItem == null) {
                    ToastUtils.showShort(this, "请选择一个骑手转单")
                    return@setOnClickListener
                }

                if (mType == TYPE_TRANSFER) {
                    ApiService.order_transfer(this, mLogisticNo!!, selectItem.id!!, object : DialogCallback<LzyResponse<Any>>() {
                        override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                            ToastUtils.showShort(this@RiderManagementActivity, "转单成功")
                            setResult(Activity.RESULT_OK)
                            finish()
                        }
                    })
                } else if (mType == TYPE_DISPATH_TRANSFER) {
                    ApiService.order_allocate(this, mLogisticNo!!, selectItem.id!!, object : DialogCallback<LzyResponse<Any>>() {
                        override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                            ToastUtils.showShort(this@RiderManagementActivity, "派单成功")
                            setResult(Activity.RESULT_OK)
                            finish()
                        }
                    })
                }
            }
        } else {
            search_cly.visibility = View.GONE
        }
        riderManagementAdapter.setType(mType)
        riderManagementAdapter.setOnItemClickListener(object : RiderManagementAdapter.OnItemClickListener {
            override fun onDelete(user: User) {
                showDeleteDialog(user)
            }

            override fun onEdit(user: User) {
                AddRiderManagementActivity.self(this@RiderManagementActivity, user, EDIT_REQUESTCODE)
            }
        })
        recLv!!.adapter = riderManagementAdapter
    }

    private fun showDeleteDialog(user: User) {
        XPopup.Builder(this) //                         .dismissOnTouchOutside(false)
                .asConfirm("", "是否确认删除？",
                        "取消", "确定",
                        OnConfirmListener {
                            ApiService.user_delete(this, user.id!!, object : DialogCallback<LzyResponse<Any>>() {
                                override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                                    notifyRemoveItem(user.id!!)
                                }
                            })
                        }, null, false)
                .show()
    }

    private fun notifyRemoveItem(id: String) {
        val data = riderManagementAdapter.data
        for (i in 0..data.size - 1) {
            val item = data.get(i)
            if (TextUtils.equals(item.id, id)) {
                data.removeAt(i)
                riderManagementAdapter.notifyItemRemoved(i)
                return
            }
        }

    }

    override fun onRightClickAction() {
        super.onRightClickAction()

        AddRiderManagementActivity.self(this, EDIT_REQUESTCODE)
    }

    override fun loadData(page: Int, pageCount: Int) {
        val searchKey = et_search.text.toString()
        ApiService.logistics_rider_list(this, searchKey, page, object : DialogCallback<LzyResponse<User>>() {
            override fun onSuccess(response: Response<LzyResponse<User>>?) {
                onGetDataSuc(response!!.body().data.records)
            }

        })
    }

    override fun getData(): MutableList<User> {
        return riderManagementAdapter.data
    }

    override fun bindData(isRefresh: Boolean, list: MutableList<User>?) {
        if (isRefresh) riderManagementAdapter.setNewData(list) else riderManagementAdapter.addData(list!!)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == EDIT_REQUESTCODE) {
                onRefresh(refreshLayout)
            }
        }
    }
}